package whf.framework.ext.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import whf.framework.entity.AbstractEntity;
import whf.framework.ext.entity.MenuItem;
import whf.framework.ext.service.MenuItemServiceImp;
import whf.framework.web.struts.WebData;
import whf.framework.web.struts.WebDispatchAction;
import whf.framework.web.struts.WebForward;

/**
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2006-06-07
 */
public class MenuItemAction extends WebDispatchAction {

	@Override
	public WebForward create(AbstractEntity webEntity, WebData data) throws Exception {
		WebForward f = super.create(webEntity, data);
		MenuItem m = (MenuItem)webEntity;
		MenuItem parent = m.getParent();
		if(parent != null){
			data.setAttribute("_$_parentId", parent.getId());
		}
		return f;
	}

	@Override
	public WebForward prepareCreate(AbstractEntity webEntity, WebData data) throws Exception {
		long parentId = data.getLongParameter("parentId", 0);
		MenuItem menu = (MenuItem)webEntity;
		if(parentId != 0){
			MenuItem parent = (MenuItem)super.getService().findByPrimaryKey(new Long(parentId));
			menu.setParent(parent);
		}
		return super.prepareCreate(menu, data);
	}

	@Override
	public WebForward update(AbstractEntity webEntity, WebData data) throws Exception {
		WebForward f = super.update(webEntity, data);
		MenuItem m = (MenuItem)webEntity;
		MenuItem parent = m.getParent();
		if(parent != null){
			data.setAttribute("parentId", parent.getId());
		}
		return f;
	}

	public WebForward forward(AbstractEntity webEntity, WebData data) throws Exception {
		long menuId = webEntity.getId();
		HttpServletRequest request = data.getRequest();
		HttpServletResponse response = data.getResponse();
		MenuItem menuItem = MenuItemServiceImp.getMenuItemService().findByPrimaryKey(menuId);
		String url = menuItem.getHref();
		if(!url.startsWith("/")) url = "/" + url;
		url = request.getContextPath() + url;
		response.sendRedirect(url);
		return null;
	}
} 